package com.cuit.utils;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author chishuiLi     Email:1192537447@qq.com
 * @Description  文件上传工具类
 */
@Component
public class FastDFSClientUtil {
    @Value("${fdfs.reqHost}")
    private String reqHost;

    @Value("${fdfs.reqPort}")
    private String reqPort;

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private ThumbImageConfig thumbImageConfig; //创建缩略图   ， 缩略图访问有问题，暂未解决


    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile((InputStream)file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);

        String path = thumbImageConfig.getThumbImagePath(storePath.getPath()) ;
        System.out.println("thumbImage :" + path);  //   缩略图访问有问题，暂未解决

        return getResAccessUrl(storePath); //返回的是完整地址 http://47.109.38.52:80/group1/M00/00/00/rBIu8WLx1jeAcasSAALrYuev-TI050.png
//        return storePath.getPath();  //group1/M00/00/00/rBIu8WLx1jeAcasSAALrYuev-TI050.png

    }

    public void delFile(String filePath) {
        storageClient.deleteFile(filePath);

    }

    public String updateFile(String oldFileName, MultipartFile newFile) throws IOException {
        storageClient.deleteFile(oldFileName);
        String[] splitString = oldFileName.split("http://" + reqHost + ":" + reqPort + "/");
        StorePath storePath = storageClient.uploadFile((InputStream)newFile.getInputStream(),newFile.getSize(),splitString[1],null);
        return getResAccessUrl(storePath);
    }

    public InputStream download(String groupName, String path ) {
        InputStream ins =  storageClient.downloadFile(groupName, path, new DownloadCallback<InputStream>(){
            @Override
            public InputStream recv(InputStream ins) throws IOException {
                // 将此ins返回给上面的ins
                return ins;
            }}) ;
        return ins ;
    }

    /**
     * 封装文件完整URL地址
     * @param storePath
     * @return 返回图片的完整路径
     */
    public String getResAccessUrl(StorePath storePath) {
        String fileUrl = "http://" + reqHost + ":" + reqPort + "/" + storePath.getFullPath();
        return fileUrl;
    }


}
